import 'package:permission_handler/permission_handler.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:rongcloud_call_wrapper_plugin/rongcloud_call_wrapper_plugin.dart';

class RCConfig {
  //  融云AppKey
  static const appKey = 'sfci50a7sm5yi';

  //  连接超时
  static const timeout = 5;

  //  测试IM用户的token（用于IM登录）
  static final LoginTokens = [
    'neZWqZLWaDInsKWyRzLlD6GdTb1JrWLX@gsgk.cn.rongnav.com;gsgk.cn.rongcfg.com',
    'n5SzUgQR10gnsKWyRzLlDz5vMYUPWDzP@gsgk.cn.rongnav.com;gsgk.cn.rongcfg.com',
    'JozkaOmawVcnsKWyRzLlD4tlxlZs91UK@gsgk.cn.rongnav.com;gsgk.cn.rongcfg.com',
    'X8rp9KCJku4nsKWyRzLlD3nU0W9Gckbv@gsgk.cn.rongnav.com;gsgk.cn.rongcfg.com',
  ];

  //  登录下标
  static int loginIndex = 0;

  //  已登录者的uid（登录IM后返回）
  static String loginUid = '';

  static RCIMIWEngine? imEngine;
  static RCCallEngine? callEngine;
  static RCIMIWConnectionStatus imStatus = RCIMIWConnectionStatus.signOut;

  static initRongCloud() async {
    await requestRCPermission();

    //  im初始化
    RCIMIWEngineOptions options = RCIMIWEngineOptions.create();
    imEngine = await RCIMIWEngine.create(RCConfig.appKey, options);

    //  Call初始化
    callEngine = await RCCallEngine.create();
  }

  static IMConnect(String token, {Function()? refresh}) async {
    await requestRCPermission();

    //  连接状态
    imEngine?.onConnectionStatusChanged = (RCIMIWConnectionStatus? status) {
      imStatus = status!;
      print('111111111');
      if (refresh != null) refresh();
    };

    //  登录回调
    int? ret = await imEngine?.connect(
      RCConfig.LoginTokens[loginIndex],
      RCConfig.timeout,
      callback: RCIMIWConnectCallback(
        onDatabaseOpened: (int? code) {},
        onConnected: (int? code, String? userId) {
          if (code == 0 && userId != null) {
            loginUid = userId!;
          }
        },
      ),
    );
    print('22222    $ret');
  }

  static requestRCPermission() async {
    // final ble = await checkBluePermission();
    final isGranted = await Permission.camera.request().isGranted;
  }
}

Future<bool> checkBluePermission() async {
  bool hasBluetoothPermission = await requestBluePermission();
  if (hasBluetoothPermission) {
    print("蓝牙权限申请通过");
    // setState(() {
    //   this.hasPermission = true;
    // });
  } else {
    print("蓝牙权限申请不通过");
    // this.hasPermission = false;
  }
  return hasBluetoothPermission;
}

Future<bool> requestBluePermission() async {
  //获取当前的权限
  var status = await Permission.bluetooth.status;
  if (status == PermissionStatus.granted) {
    //已经授权
    return true;
  } else {
    //未授权则发起一次申请
    status = await Permission.bluetooth.request();
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      return false;
    }
  }
}
